package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Clubs;
import com.ruoyi.system.domain.Members;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.es.ClubDocument;
import com.ruoyi.system.es.ClubRepository;
import com.ruoyi.system.mapper.ClubsMapper;
import com.ruoyi.system.mapper.MembersMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.IClubsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 社团基本信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-27
 */
@Service
public class ClubsServiceImpl implements IClubsService {
    @Autowired
    private ClubsMapper clubsMapper;
    @Autowired
    private MembersMapper membersMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private ClubRepository clubRepository;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询社团基本信息
     *
     * @param clubId 社团基本信息主键
     * @return 社团基本信息
     */
    @Override
    public Clubs selectClubsByClubId(Long clubId) {

        Clubs clubs = clubsMapper.selectClubsByClubId(clubId);
        Members members = new Members();
        members.setClubId(clubs.getClubId());
        List<Members> membersList = membersMapper.selectMembersList(members);
        clubs.setMembersList(membersList);
        return clubs;
    }

    /**
     * 查询社团基本信息列表
     *
     * @param clubs 社团基本信息
     * @return 社团基本信息
     */
    @Override
    public List<Clubs> selectClubsList(Clubs clubs) {
        Long userId = SecurityUtils.getUserId();
        List<SysRole> sysRoles = sysRoleMapper.selectRolesByUserId(userId);
        List<String> roleName = sysRoles.stream().map(SysRole::getRoleName).collect(Collectors.toList());
        PageUtils.startPage();
        if (roleName.contains("超级管理员")) {
            List<Clubs> clubsList = clubsMapper.selectClubsList(clubs);
            //clubsList
            List<Long> ids = clubsList.stream().map(Clubs::getClubId).collect(Collectors.toList());
            //查询用户申请表
            if(CollUtil.isNotEmpty(ids)){
                Map<Long, List<Members>> collect = membersMapper.selectMembersListByClubIds(ids).stream().collect(Collectors.groupingBy(Members::getClubId));
                clubsList.forEach(item -> {
                    List<Members> orDefault = collect.getOrDefault(item.getClubId(), Collections.emptyList());
                    item.setMemberCount(orDefault.size());
                });
            }
            return clubsList;
        }
        List<Clubs> clubsList = clubsMapper.selectListByUserId(clubs, userId);
        List<Long> ids = clubsList.stream().map(Clubs::getClubId).collect(Collectors.toList());
        Map<Long, List<Members>> collect = new HashMap<>();
        if (CollUtil.isNotEmpty(ids)) {
            collect.putAll(membersMapper.selectMembersListByClubIds(ids).stream().collect(Collectors.groupingBy(Members::getClubId)));
        }
        //查询用户申请表
        clubsList.forEach(item -> {
            List<Members> orDefault = collect.getOrDefault(item.getClubId(), Collections.emptyList());
            item.setMemberCount(orDefault.size());
        });
        return clubsList;
    }

    /**
     * 新增社团基本信息
     *
     * @param clubs 社团基本信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertClubs(Clubs clubs) {
        Long uId = SecurityUtils.getUserId();
        String auth = SecurityUtils.getUsername();
        clubs.setCurrentLeaderId(uId);
        clubs.setCurrentLeaderName(auth);
        clubs.setStatus("待审核");
        int result = clubsMapper.insertClubs(clubs);
        if (result > 0) {
            ClubDocument doc = new ClubDocument();
            doc.setSId(clubs.getClubId().toString());
            doc.setId(clubs.getClubId()+":club");
            doc.setClubName(clubs.getName());
            doc.setDescription(clubs.getDescription());
            doc.setCurrentLeaderName(clubs.getCurrentLeaderName());
            doc.setCreateTime(clubs.getCreateTime());
            clubRepository.save(doc);
        }
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        Members members = new Members();

        members.setUserId(userId);
        members.setClubName(members.getClubName());
        members.setUserName(username);
        members.setClubId(clubs.getClubId());
        members.setCreatedAt(new Date());
        members.setRole(2);
        members.setStatus(2);
        membersMapper.insertMembers(members);
        SysUserRole sysUserRole = new SysUserRole();
        List<SysUserRole> list = new ArrayList<>();
        sysUserRole.setRoleId(100L);
        sysUserRole.setUserId(userId);
        list.add(sysUserRole);
        try {
            sysUserRoleMapper.batchUserRole(list);
        } catch (Exception e) {


        }
        return result;
    }

    /**
     * 修改社团基本信息
     *
     * @param clubs 社团基本信息
     * @return 结果
     */
    @Override
    public int updateClubs(Clubs clubs) {
        int result = clubsMapper.updateClubs(clubs);
//        if (result > 0) {
//            ClubDocument doc = new ClubDocument();
//            doc.setSId(clubs.getClubId().toString());
//            doc.setId(clubs.getClubId()+":club");
//            doc.setClubName(clubs.getName());
//            doc.setDescription(clubs.getDescription());
//            doc.setCurrentLeaderName(clubs.getCurrentLeaderName());
//            doc.setCreateTime(clubs.getCreateTime());
//            clubRepository.save(doc);
//        }
        return result;
    }

    /**
     * 批量删除社团基本信息
     *
     * @param clubIds 需要删除的社团基本信息主键
     * @return 结果
     */
    @Override
    public int deleteClubsByClubIds(Long[] clubIds) {
        return clubsMapper.deleteClubsByClubIds(clubIds);
    }

    /**
     * 删除社团基本信息信息
     *
     * @param clubId 社团基本信息主键
     * @return 结果
     */
    @Override
    public int deleteClubsByClubId(Long clubId) {
        int result = clubsMapper.deleteClubsByClubId(clubId);
        if (result > 0) {
            clubRepository.deleteById(clubId+":club");
        }
        return result;
    }

    @Override
    public List<Clubs> selectClubsListByUser(Clubs clubs, Long userId) {
        clubs.setApplyId(userId);
        List<Clubs> clubsList = clubsMapper.selectClubsListByUser(clubs, userId);
        return clubsList;
    }

    @Override
    public Clubs selectClubsByUser(Long clubId) {
        Clubs clubs = new Clubs();
        clubs.setClubId(clubId);
        Long userId = SecurityUtils.getUserId();
        List<Clubs> clubsList = clubsMapper.selectClubsListByUser(clubs, userId);
        Clubs obj = clubsList.get(0);
        if (null != obj) {
            if (null == obj.getUserStatus()) {
                obj.setUserStatus(0);
            }
        }
        return obj;
    }

    @Override
    public List<Clubs> selectUserClubs(Long userId) {
        return clubsMapper.selectUserClubs(userId);
    }

    @Override
    public List<Clubs> selectClubsListByVisitor(Clubs clubs) {
        return clubsMapper.selectClubsList(clubs);
    }
}
